package com.cloudkinto.service.platform.impl;

import cn.afterturn.easypoi.csv.entity.CsvExportParams;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.RabbitQueueConstant;
import com.cloudkinto.common.RedisKeyConstants;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.*;
import com.cloudkinto.common.utils.ali.AliOss;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.dao.*;
import com.cloudkinto.dto.platform.PlatOrderUpdateTimeDto;
import com.cloudkinto.entity.*;
import com.cloudkinto.enumType.common.CountryEnum;
import com.cloudkinto.enumType.operate.OperateTypeEnum;
import com.cloudkinto.service.consumer.vo.StockToPlatformConsumerReq;
import com.cloudkinto.service.consumer.vo.order.PlatformOrderCancelReq;
import com.cloudkinto.service.consumer.vo.order.UpdateInventoryLessReq;
import com.cloudkinto.service.consumer.vo.orderSyncRecord.PlatformOrderSyncRecordReq;
import com.cloudkinto.service.consumer.vo.rakuten.ItemUpdateConsumerReq;
import com.cloudkinto.service.consumer.vo.rakuten.RakutenOrderUpdateConReq;
import com.cloudkinto.service.consumer.vo.shopify.WowmaConsumerReq;
import com.cloudkinto.service.consumer.vo.wowma.WowmaMarkStatusConsumer;
import com.cloudkinto.service.consumer.vo.wowma.WowmaMarkShipConsumerReq;
import com.cloudkinto.service.mail.MailAccountService;
import com.cloudkinto.service.mail.SendMailService;
import com.cloudkinto.service.mail.vo.SendMailConsumerReq;
import com.cloudkinto.service.platform.PlatformOrderService;
import com.cloudkinto.service.platform.PlatformOrderWowmaSyncService;
import com.cloudkinto.service.platform.PlatformProductService;
import com.cloudkinto.service.platform.PlatformStoreService;
import com.cloudkinto.service.platform.sync.vo.SyncRecordItemReq;
import com.cloudkinto.service.platform.vo.rakuten.PlatformProductSyncReq;
import com.cloudkinto.service.platform.vo.AsyncFinishConsumerReq;
import com.cloudkinto.service.platform.vo.AsyncUpdateConsumerReq;
import com.cloudkinto.service.platform.vo.StockToPlatformRecordVo;
import com.cloudkinto.service.platform.vo.wowma.*;
import com.cloudkinto.vo.stock.PlatformSkuStockDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jdom2.JDOMException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author ding
 * @since 2021-09-23
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)//事务回滚
@RequiredArgsConstructor
public class PlatformOrderWowmaSyncServiceImpl extends ServiceImpl<PlatformOrderDao, PlatformOrderDo> implements PlatformOrderWowmaSyncService {
    private final PlatformStoreDao platformStoreDao;
    private final PlatformOrderDao platformOrderDao;
    private final RabbitTemplate rabbitTemplate;
    private final PlatformOrderProductDao platformOrderProductDao;
    private final PlatformOrderService platformOrderService;
    private final PlatformStoreService platformStoreService;
    private final RedisTemplate redisTemplate;
    @Value("${gbc.customer}")
    private String customer;
    private final SendMailService mailSendService;
    private final MailAccountService mailAccountService;
    private final ThreadPoolTaskExecutor taskExecutor;
    private final ProductStockDao productStockDao;
    @Value("${gbc.exportPath.omsFilePath}")
    private String omsFilePath;
    @Value("${gbc.uploadPath.omsFileUrl}")
    private String omsFileUrl;
    @Value("${gbc.uploadPath.fileUrl}")
    private String fileUrl;
    @Value("${gbc.uploadPath.filePath}")
    private String filePath;
    private final AsyncJobDao asyncJobDao;
    private final PlatformOrderSyncRecordDao platformOrderSyncRecordDao;
    private final PlatformProductService platformProductService;

    @Override
    public void platOrderWowmaSync() {
        List<PlatformStoreDo> storeDoList = platformStoreDao.selectList(new LambdaQueryWrapper<PlatformStoreDo>().eq(PlatformStoreDo::getPlatformCode, "wowma")
                .eq(PlatformStoreDo::getAuthSyncStatus, 1).isNotNull(PlatformStoreDo::getAppSecret));
        Map<Long, Long> storeRecordIdMap = new HashMap<>();
        for (PlatformStoreDo storeDo : storeDoList) {
            PlatformOrderSyncRecordDo recordDo = new PlatformOrderSyncRecordDo(storeDo.getPlatformCode(), storeDo.getId(), 1, 0, 0, new Date(), null, storeDo.getCompanyId());
            platformOrderSyncRecordDao.insert(recordDo);
            storeRecordIdMap.put(storeDo.getId(), recordDo.getId());
        }
        for (PlatformStoreDo platformStoreDo : storeDoList) {
            Long syncRecordId = storeRecordIdMap.get(platformStoreDo.getId());
            if (syncRecordId == null) {
                continue;
            }
            WowmaConsumerReq consumerReq = new WowmaConsumerReq(platformStoreDo.getId(), null, null, syncRecordId);
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_Sync, JSON.toJSONString(consumerReq));
        }
    }


    @Override
    public Object testGetOrderByNumber(String orderNumber, Long storeId) {
        PlatformStoreDo storeDo = platformStoreDao.selectById(storeId);
        WowmaApiRes orderByOrderId = this.getOrderByOrderId(storeDo, orderNumber);
//        log.error("yahoo 测试" + orderNumber + ":\r\n" + orderByOrderId);

//        String apiUrl = "https://api.mercari-shops-sandbox.com/v1/graphql/productCategories";
//        String jsonData = null;
//        try {
//            jsonData = WowmaUtil.raAPidoGet(apiUrl, "msp_XKVxiWQyTfnmjhDdyHpt8N_X3UhE7JsXXtGTi9FAqXdyE7DhPwsmBiZ9hcjnNCyCJw", new HashMap<>());
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        System.out.println(jsonData);
        return orderByOrderId;
    }


    @Override
    public String updatWowmaOrders(WowmaConsumerReq req) {
        PlatformStoreDo storeDo = platformStoreDao.selectById(req.getStoreId());
        if (storeDo == null) {
            return SysConstant.Shop_NotExist;
        }
        boolean flag = req.getStartDate() == null;
        //自动
        if (!flag) {
            long l = DateUtil.betweenDay(req.getStartDate(), req.getEndDate(), true);
            if (l > 7) {
                return "Wowma店铺:" + storeDo.getStoreName() + "每次最多同步7天数据";
            }
        }
        Object lastStartCount = null;
        if (flag) { //自动
            Double time = redisTemplate.opsForZSet().score(RedisKeyConstants.orderSyncTimeSet_Wowma + customer, storeDo.getId());
            long currency = System.currentTimeMillis();
            if (!(time == null || (currency - time) >= 60 * 5 * 1000)) {
//                return "Wowma 同步频率过快(5分钟同步一次)";
            }
            //无上次同步时间 或者 上次同步时间在10分钟之前
            redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Wowma + customer, storeDo.getId(), currency - 30 * 60 * 1000);
            req.setStartDate(DateUtils.passingDate(new Date(), -1));
            req.setEndDate(new Date(currency));
            long l = DateUtil.betweenDay(req.getStartDate(), new Date(), true);
            if (l > 3) {
                req.setStartDate(DateUtils.passingDate(new Date(), -3));
            }
//            req.setStartDate(DateUtils.passingDate(new Date(), -1));
            if (time == null) {
                lastStartCount = 1;
            } else {
                lastStartCount = redisTemplate.opsForValue().
                        get(RedisKeyConstants.orderSyncStartCountSet_Wowma + storeDo.getId() + "_" + customer + "_" + DateUtils.dateFormatToString(req.getStartDate()));
            }
        }

        String url = "https://api.manager.wowma.jp/wmshopapi/searchTradeInfoListProc";
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("startDate", DateUtils.dateFormatToString(req.getStartDate(), "yyyy-MM-dd"));
        bodyMap.put("endDate", DateUtils.dateFormatToString(req.getEndDate(), "yyyy-MM-dd"));
        bodyMap.put("shopId", storeDo.getSellerId());
        bodyMap.put("dateType", 0);//入金日//0:注文日　1:発送日　2:入金日　3:発売(入荷)予定日　4:発送期限日　（デフォルト0）
        int totalCount = 1000;
        bodyMap.put("totalCount", totalCount);
//        int existOrderCount = lastStartCount == null ? 1 : Integer.parseInt(lastStartCount.toString());
        int startCount = 1;
        //告诉他正在处理
        rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_SyncRecord_Update, JSON.toJSONString(new PlatformOrderSyncRecordReq(req.getSyncId(), 1, new Date(), req.getStartDate(), req.getEndDate())));
        List<OrderWowmaEntity> entities = new ArrayList<>();
        int resultCount = 0;
        do {
            bodyMap.put("startCount", startCount);
//            log.error("wowma订单请求值：\r\n" + JSON.toJSONString(bodyMap));
            String jsonData = null;
            try {
                jsonData = WowmaUtil.raAPidoGet(url, storeDo.getAppSecret(), bodyMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isBlank(jsonData)) {
                return "Wowma店铺：" + storeDo.getStoreName() + "连接超时";
            }
//            log.error("wowma订单返回值：\r\n" + jsonData);
            JSONObject object = null;
            List<OrderWowmaEntity> list = null;
            try {
                object = XmlUtils.xml2Json(jsonData);
            } catch (JDOMException | IOException e) {
                e.printStackTrace();
            }
            if (object == null || object.get("response") == null || object.getJSONObject("response").getString("result") == null) {
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Wowma + customer, storeDo.getId(), req.getStartDate().getTime());
                }
                return "Wowma 获取订单列表 xml格式解析空指针";
            }
            JSONObject result = object.getJSONObject("response").getJSONArray("result").getJSONObject(0);
            if (StringUtils.isBlank(result.getString("status"))) {
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Wowma + customer, storeDo.getId(), req.getStartDate().getTime());
                }
                return "Wowma 获取订单列表 status 获取失败";
            } else if ("1".equals(result.getString("status"))) {
                if (flag) {
                    redisTemplate.opsForZSet().add(RedisKeyConstants.orderSyncTimeSet_Wowma + customer, storeDo.getId(), req.getStartDate().getTime());
                }
                JSONObject error = result.getJSONArray("error").getJSONObject(0);
                if ("0002".equals(error.getString("code"))) {
                    //message -> 認証に失敗しました。 授权过期了
                    platformStoreService.updateStoreAuthStatus(storeDo.getId());
                }
                return error.getString("message");
            } else {
                resultCount = object.getJSONObject("response").getIntValue("resultCount");
                list = JSONArray.parseArray(object.getJSONObject("response").getString("orderInfo"), OrderWowmaEntity.class);
                startCount += resultCount;
//                log.error("wowma订单resultCount("+storeDo.getSellerId()+")：" + resultCount);
            }
            if (list != null && !list.isEmpty()) {
                entities.addAll(list);
            } else {
                break;
            }

        } while (resultCount >= totalCount);

        //获取这些订单的 最近更新时间
        List<String> platformOrders = entities.stream().map(i -> String.valueOf(i.getOrderId())).collect(Collectors.toList());
        Map<String, PlatOrderUpdateTimeDto> orderMap = new HashMap<>();
        if (!platformOrders.isEmpty()) {
            List<List<String>> partition = ListUtil.partition(platformOrders, 5000);
            for (List<String> list : partition) {
                List<PlatOrderUpdateTimeDto> platOrder = platformOrderDao.getPlatOrder(list, storeDo.getId(), "wowma");
                orderMap.putAll(platOrder.stream().collect(Collectors.toMap(PlatOrderUpdateTimeDto::getPlatformOrderNo, i -> i, (i1, i2) -> i1)));
            }
        }

        //组装
        //要插入的
        List<PlatformOrderDo> platInertList = new ArrayList<>();
        //要更新 子表的的
        List<PlatformOrderDo> platUpdateList = new ArrayList<>();

        //子表插入的
        List<PlatformOrderProductDo> platInsertItems = new ArrayList<>();
        List<PlatformOrderProductDo> platUpdateItems = new ArrayList<>();
        List<WowmaMarkStatusReq> markStatusHasPayList = new ArrayList<>();
        List<WowmaMarkStatusReq> markStatusNoPayList = new ArrayList<>();
        for (OrderWowmaEntity amzOrder : entities) {
            PlatOrderUpdateTimeDto oldUpdateTime = orderMap.get(String.valueOf(amzOrder.getOrderId()));
            if (oldUpdateTime != null &&
                    (StaticDict.Platform_Order_Status.Three.getValue().equals(oldUpdateTime.getStatus()) || StaticDict.Platform_Order_Status.Four.getValue().equals(oldUpdateTime.getStatus()))) {
                //本地订单是已完成状态
                continue;
            }
            //如果最近更新时间 和子表都同步下来了 就不需要在操作了
//            if (oldUpdateTime != null && Objects.equals(oldUpdateTime.getLastUpdateDate().getTime(), platUpdateTIme.getTime())) {
//                //更新日期相等
//                continue;
//            }
            PlatformOrderDo orderDo = new PlatformOrderDo();
            if (StringUtils.isNotBlank(amzOrder.getPaymentDate())) {
                orderDo.setPayTime(DateUtil.parse(amzOrder.getPaymentDate(), "yyyy/MM/dd HH:mm"));
            }
            if ("キャンセル".equals(amzOrder.getOrderStatus())) {
                //取消
                orderDo.setStatus(StaticDict.Platform_Order_Status.Four.getValue());
                orderDo.setCancelWay(0);
                if (StringUtils.isNotBlank(amzOrder.getCancelDate())) {
                    orderDo.setCancelTime(DateUtil.parse(amzOrder.getCancelDate(), "yyyy/MM/dd HH:mm"));
                }
            } else if ("完了".equals(amzOrder.getOrderStatus())) {
                orderDo.setStatus(StaticDict.Platform_Order_Status.Three.getValue());
                if (StringUtils.isNotBlank(amzOrder.getShipDate())) {
                    orderDo.setShipTime(DateUtil.parse(amzOrder.getShipDate(), "yyyy/MM/dd HH:mm"));
                }
//                orderDo.setMarkShipmentStatus(4);
                //发货时间
            }
//            else if ("与信待ち".equals(amzOrder.getOrderStatus()) || "発送待ち".equals(amzOrder.getOrderStatus())) {
//                //可以发货
//                if (oldUpdateTime == null || oldUpdateTime.getStatus() == -1) {
//                    orderDo.setStatus(StaticDict.Platform_Order_Status.Zero.getValue());
//                }
//                if (orderDo.getPayTime() == null) {
//                    orderDo.setPayTime(new Date());
//                }
//            }
            else if ("新規受付".equals(amzOrder.getOrderStatus()) || "発送前入金待ち".equals(amzOrder.getOrderStatus())
                    || "発送後入金待ち".equals(amzOrder.getOrderStatus())) {
                //不能发货 等待付款
                if (oldUpdateTime == null) {
                    orderDo.setStatus(0);
                }
                if ("新規受付".equals(amzOrder.getOrderStatus())) {
                    if ("銀行振込".equals(amzOrder.getSettlementName())) {
                        markStatusNoPayList.add(new WowmaMarkStatusReq(oldUpdateTime == null ? 0L : oldUpdateTime.getId(), amzOrder.getOrderId()));
                    } else {
                        if (orderDo.getPayTime() == null) {
                            orderDo.setPayTime(new Date());
                        }
                        markStatusHasPayList.add(new WowmaMarkStatusReq(oldUpdateTime == null ? 0L : oldUpdateTime.getId(), amzOrder.getOrderId()));
                    }
                }
            } else {
                //与信待ち 発送待ち  这两个状态可以发货 目前不限制 看看
                if (oldUpdateTime == null) {
                    orderDo.setStatus(StaticDict.Platform_Order_Status.Zero.getValue());
                }
                if (orderDo.getPayTime() == null) {
                    orderDo.setPayTime(new Date());
                }
            }
            if (oldUpdateTime != null && oldUpdateTime.getPayTime() != null && (orderDo.getStatus() == null || orderDo.getStatus() == (oldUpdateTime.getStatus()))) {
                continue;
            }
            orderDo.setCompanyId(storeDo.getCompanyId());
            orderDo.setTenantId(storeDo.getTenantId());
            orderDo.setPlatformCode(storeDo.getPlatformCode());
            orderDo.setStoreId(storeDo.getId());
            orderDo.setSite(storeDo.getSite());
            orderDo.setOrderTime(DateUtil.parse(amzOrder.getOrderDate(), "yyyy/MM/dd HH:mm"));
//            orderDo.setLastUpdateDate(new Date());
            orderDo.setPlatformOrderNo(amzOrder.getOrderId());
            //收货人信息
            orderDo.setReceiver(amzOrder.getSenderName());
            orderDo.setTelephone((StringUtils.isNotBlank(amzOrder.getSenderPhoneNumber2()) ? amzOrder.getSenderPhoneNumber2() : amzOrder.getSenderPhoneNumber1()));
            orderDo.setCountryRegionCode(CountryEnum.JP.toString());
            String addr1 = amzOrder.getSenderAddress();
//            if (address.contains("県")) {
//                String district = address.substring(0, address.indexOf("県") + 1);
//                orderDo.setDistrict(district.trim());
//                address = address.substring(address.indexOf("県") + 1);
//            }
//            if (address.contains("市")) {
//                String cityCode = address.substring(0, address.indexOf("市") + 1);
//                orderDo.setCityCode(cityCode.trim());
//                address = address.substring(address.indexOf("市") + 1);
//            }

            if (StringUtils.isNotBlank(addr1)) {
                int index1 = addr1.indexOf("県");
                int index2 = addr1.indexOf("都");
                int index3 = addr1.indexOf("道");
                int index4 = addr1.indexOf("府");
                List<Integer> indexList = new ArrayList<>();
                if (index1 != -1) {
                    indexList.add(index1);
                }
                if (index2 != -1) {
                    indexList.add(index2);
                }
                if (index3 != -1) {
                    indexList.add(index3);
                }
                if (index4 != -1) {
                    indexList.add(index4);
                }
                Collections.sort(indexList);
                if (indexList.isEmpty()) {
                    orderDo.setDistrict("");
                    orderDo.setAddressOne(addr1);
                } else {
                    int firstIndex = indexList.get(0) < 2 ? indexList.get(0) + 1 : indexList.get(0);
                    orderDo.setDistrict(addr1.substring(0,  firstIndex + 1));
                    orderDo.setAddressOne(addr1.substring(firstIndex + 1));
                }
            }
//            orderDo.setProvinceCode("");
            orderDo.setProvinceName("");
            orderDo.setPostcode(amzOrder.getSenderZipCode());
            orderDo.setHouseNum("");
            orderDo.setAddressTwo("");
            orderDo.setSettlementModel(amzOrder.getSettlementName());
            //买家信息
            orderDo.setBuyerName(amzOrder.getOrdererName());
            orderDo.setBuyerEmail(amzOrder.getMailAddress());
            orderDo.setBuyerAddress(amzOrder.getOrdererAddress());
            orderDo.setBuyerPostcode(amzOrder.getOrdererZipCode());
            orderDo.setBuyerTelephone(amzOrder.getOrdererPhoneNumber1());
            //总金额
            orderDo.setTotalAmount(BigDecimal.valueOf(amzOrder.getTotalSalePrice()));
            orderDo.setCurrencyCode(CountryEnum.JP.getCurrency());
            orderDo.setPostagePrice(new BigDecimal(amzOrder.getPostagePrice()));
            orderDo.setReqPrice(new BigDecimal(amzOrder.getRequestPrice()));
            orderDo.setCoupon(new BigDecimal(amzOrder.getCouponTotalPrice()));
            orderDo.setPoint(BigDecimal.valueOf(amzOrder.getUsePoint() + amzOrder.getUseAuPoint()));
            orderDo.setDefaultDeliveryCompanyCode(amzOrder.getDeliveryName());
            orderDo.setRemark(amzOrder.getMemo());
            orderDo.setReserveFlag(0);
            //预约单
            if ("2".equals(amzOrder.getSellMethodSegment())) {
                orderDo.setReserveFlag(1);
            }
            if (StringUtils.isNotBlank(amzOrder.getReleaseDate())) {
                orderDo.setReserveEndTime(DateUtil.parse(amzOrder.getReleaseDate()));
                orderDo.setReserveBeginTime(orderDo.getOrderTime());
            }
            //todo 这里是 发送期限日
            Date shippingTimelimitDate = null;
            StringBuilder builder = new StringBuilder();
            StringBuilder platformSku = new StringBuilder();
            for (OrderWowmaEntity.DetailDTO line_item : amzOrder.getDetail()) {
                PlatformOrderProductDo platItem = new PlatformOrderProductDo();
//                platItem.setOrderId(toUpdateItem.getId());
                platItem.setPlatformOrderNo(String.valueOf(amzOrder.getOrderId()));
                platItem.setPlatformParentSku(line_item.getItemCode());
                platItem.setPlatformSku(line_item.getItemManagementId());
                platItem.setPlatformProductName(line_item.getItemName());
                platItem.setSkuInfo(line_item.getItemOption());
                platItem.setPlatformQty(line_item.getUnit());
                platItem.setSkuType(1);
                platItem.setItemAmount(BigDecimal.valueOf(line_item.getItemPrice()));
                platItem.setCurrencyCode(CountryEnum.JP.getCurrency());
                if (StringUtils.isNotBlank(builder.toString())) {
                    builder.append("\r\n");
                }
                builder.append(line_item.getShippingDayDispText()).append("------").append(line_item.getShippingTimelimitDate());
                if (StringUtils.isNotBlank(platformSku.toString())) {
                    platformSku.append(";");
                }
                platformSku.append(platItem.getPlatformSku()).append("*").append(platItem.getPlatformQty());
                if (oldUpdateTime != null) {
                    platItem.setOrderId(oldUpdateTime.getId());
                    platUpdateItems.add(platItem);
                } else {
                    platInsertItems.add(platItem);
                }
            }
            if (platformSku.length() > 100) {
                builder.delete(100, platformSku.length());
            }
            orderDo.setPlatformSku(platformSku.toString());
            if (StringUtils.isNotBlank(builder.toString())) {
                orderDo.setOrderNo(builder.toString());
            }
            if (oldUpdateTime != null) {
                orderDo.setId(oldUpdateTime.getId());
                platUpdateList.add(orderDo);
            } else {
                platInertList.add(orderDo);
            }
        }

        if (!platInertList.isEmpty()) {
            platformOrderService.matchSystemSku(platInsertItems, storeDo.getId(), storeDo.getCompanyId(), storeDo.getTenantId());
            Map<String, List<PlatformOrderProductDo>> skuMap = platInsertItems.stream().filter(i -> StringUtils.isNotBlank(i.getSku())).collect(Collectors.groupingBy(PlatformOrderProductDo::getPlatformOrderNo));
            List<PlatformOrderDo> insertList = platInertList.stream().filter(i -> skuMap.containsKey(i.getPlatformOrderNo())).collect(Collectors.toList());
            for (PlatformOrderDo orderDo : insertList) {
                if (skuMap.get(orderDo.getPlatformOrderNo()) == null) {
                    continue;
                }
                StringBuilder builder = new StringBuilder();
                for (PlatformOrderProductDo productDo : skuMap.get(orderDo.getPlatformOrderNo())) {
                    if (StringUtils.isNotBlank(builder.toString())) {
                        builder.append(";");
                    }
                    builder.append(productDo.getSku()).append("*").append(productDo.getQty());
                }
                if (builder.length() > 100) {
                    builder.delete(100, builder.length());
                }
                orderDo.setSku(builder.toString());
            }
            platformOrderDao.insertPlatformOrder(platInertList);
            for (PlatformOrderDo orderDo : platInertList) {
                //去赋值 orderId
                platInsertItems.stream().filter(i -> i.getPlatformOrderNo().equals(orderDo.getPlatformOrderNo())).forEach(item -> item.setOrderId(orderDo.getId()));
                for (WowmaMarkStatusReq statusReq : markStatusNoPayList) {
                    if (statusReq.getOrderId().equals(orderDo.getPlatformOrderNo())) {
                        statusReq.setId(orderDo.getId());
                        break;
                    }
                }
                for (WowmaMarkStatusReq statusReq : markStatusNoPayList) {
                    if (statusReq.getOrderId().equals(orderDo.getPlatformOrderNo())) {
                        statusReq.setId(orderDo.getId());
                        break;
                    }
                }
            }
        }
        //插入子表
        if (!platInsertItems.isEmpty()) {
            platformOrderProductDao.insertPlatformOrderItems(platInsertItems);
        }
        if (req.getStartDate() != null) {
            redisTemplate.opsForValue().set(RedisKeyConstants.orderSyncStartCountSet_Wowma + storeDo.getId() + "_" + customer + "_" + DateUtils.dateFormatToString(req.getStartDate()), startCount, 30 * 60, TimeUnit.SECONDS);
        }
        if (!markStatusHasPayList.isEmpty())
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_MarkStatus, JSON.toJSONString(
                    new WowmaMarkStatusConsumer(markStatusHasPayList, "発送待ち", storeDo, null)));
        if (!markStatusNoPayList.isEmpty())
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_MarkStatus, JSON.toJSONString(
                    new WowmaMarkStatusConsumer(markStatusNoPayList, "発送前入金待ち", storeDo, null)));

        //分别去插入更新
        if (!platUpdateList.isEmpty()) {
            //再交给rabbitMq 去更新子表
            for (PlatformOrderDo orderDo : platUpdateList) {
                List<PlatformOrderDo> array = new ArrayList<>(Collections.singletonList(orderDo));
                List<PlatformOrderProductDo> collect = platUpdateItems.stream().filter(i -> Objects.equals(orderDo.getId(), i.getOrderId())).collect(Collectors.toList());
                rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_Update, JSON.toJSONString(new RakutenOrderUpdateConReq(array, collect, storeDo.getId(), storeDo.getCompanyId(), storeDo.getTenantId())));
            }
        }
        //去同步本地未完成的订单
        if (flag) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_Update_Sync, storeDo.getId());
        }
        //完成
        List<SyncRecordItemReq> items = platInertList.stream().map(i -> new SyncRecordItemReq(i.getId(), i.getPlatformOrderNo(), storeDo.getId(), storeDo.getCompanyId())).collect(Collectors.toList());
        rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_SyncRecord_Update, JSON.toJSONString(new PlatformOrderSyncRecordReq(req.getSyncId(), 2, new Date(), null, null, platInertList.size(), items)));
        if (flag) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.StockToPlatform_CreateStockToPlatformAfterSync, storeDo.getId()+"");
        }
        return "";
    }


//    public void updateLocalOrders() {
//        List<PlatformStoreDo> storeDoList = platformStoreDao.selectList(new LambdaQueryWrapper<PlatformStoreDo>().eq(PlatformStoreDo::getPlatformCode, "wowma")
//                .eq(PlatformStoreDo::getAuthSyncStatus, 1).isNotNull(PlatformStoreDo::getServiceToken));
//        for (PlatformStoreDo platformStoreDo : storeDoList) {
//            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_Update_Sync, platformStoreDo.getId());
//        }
//    }

    @Override
    public void updateLocalOrders(Long storeId) {
        //每四次自动同步 同步一次
        Object o = redisTemplate.opsForValue().
                get(RedisKeyConstants.orderSyncTimeCountSet_Wowma + storeId + "_" + customer + "_" + DateUtils.dateFormatToString(new Date()));
        LocalTime now = LocalTime.now();
        int hour = now.getHour();
        if (o != null && Integer.parseInt(o.toString()) % 8 != 0 && hour != 11) {
            return;
        }
        int timeCount = o == null ? 0 : Integer.parseInt(o.toString()) + 1;
        redisTemplate.opsForValue().set(RedisKeyConstants.orderSyncTimeCountSet_Wowma + storeId + "_" + customer + "_" + DateUtils.dateFormatToString(new Date()), timeCount, 6 * 60 * 60, TimeUnit.SECONDS);
        List<PlatformOrderDo> orderDos = platformOrderDao.selectList(new LambdaQueryWrapper<PlatformOrderDo>().eq(PlatformOrderDo::getStoreId, storeId)
                .in(PlatformOrderDo::getStatus, StaticDict.Platform_Order_Status.Zero.getValue(), StaticDict.Platform_Order_Status.Five.getValue())
                .eq(PlatformOrderDo::getPlatformCode, "wowma")
                .ge(PlatformOrderDo::getOrderTime, DateUtils.dateFormatToString(DateUtils.passingDate(new Date(), -30)))
//                .le(PlatformOrderDo::getOrderTime, DateUtils.dateFormatToString(DateUtils.passingDateMin(new Date(), -30)))
        );
        if (orderDos.isEmpty()) {
            return;
        }
        Map<String, PlatformOrderDo> payTimeMap = orderDos.stream().collect(Collectors.toMap(PlatformOrderDo::getPlatformOrderNo, i -> i, (i1, i2) -> i1));
        List<String> orderNumbers = orderDos.stream().filter(i -> i.getPayTime() == null).map(PlatformOrderDo::getPlatformOrderNo).collect(Collectors.toList());
        PlatformStoreDo storeDo = platformStoreDao.selectById(storeId);
        List<String> cancelOrderNos = new ArrayList<>();
        for (String object : orderNumbers) {
            WowmaApiRes orderByOrderId = this.getOrderByOrderId(storeDo, object);
            if (orderByOrderId.getCode() != 200) {
                continue;
            }
            if ("認証に失敗しました".equals(orderByOrderId.getMsg())) {
                break;
            }
            if (orderByOrderId.getData().isEmpty()) {
                continue;
            }
            OrderWowmaEntity amzOrder = orderByOrderId.getData().get(0);

            PlatformOrderDo oldOrder = payTimeMap.get(object);
            if (oldOrder == null) {
                continue;
            }
            LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(PlatformOrderDo::getId, oldOrder.getId());

            if ("キャンセル".equals(amzOrder.getOrderStatus())) {
                updateWrapper.set(PlatformOrderDo::getStatus, StaticDict.Platform_Order_Status.Four.getValue());
                updateWrapper.set(PlatformOrderDo::getCancelWay, 0);
                //取消
                updateWrapper.set(StringUtils.isNotBlank(amzOrder.getCancelDate()), PlatformOrderDo::getCancelTime, DateUtil.parse(amzOrder.getCancelDate(), "yyyy/MM/dd HH:mm"));

                if (!Objects.equals(oldOrder.getStatus(), StaticDict.Platform_Order_Status.Four.getValue())) {
                    cancelOrderNos.add(object);
                }
            } else if ("完了".equals(amzOrder.getOrderStatus())) {
                updateWrapper.set(PlatformOrderDo::getStatus, StaticDict.Platform_Order_Status.Three.getValue());
                updateWrapper.set(StringUtils.isNotBlank(amzOrder.getShipDate()), PlatformOrderDo::getShipTime, DateUtil.parse(amzOrder.getShipDate(), "yyyy/MM/dd HH:mm"));
            } else if ("新規受付".equals(amzOrder.getOrderStatus()) || "発送前入金待ち".equals(amzOrder.getOrderStatus())
                    || "発送後入金待ち".equals(amzOrder.getOrderStatus())) {
                //不能发货 等待付款
                continue;
            } else {
                //与信待ち 発送待ち  这两个状态可以发货 目前不限制 看看
                if (oldOrder.getPayTime() != null) {
                    continue;
                }
                updateWrapper.set(PlatformOrderDo::getPayTime, StringUtils.isNotBlank(amzOrder.getPaymentDate()) ? DateUtil.parse(amzOrder.getPaymentDate(), "yyyy/MM/dd HH:mm") : new Date());
            }
            platformOrderDao.update(null, updateWrapper);
        }
        if (!cancelOrderNos.isEmpty()) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_CancelForBound, JSON.toJSONString(new PlatformOrderCancelReq(storeDo.getId(), cancelOrderNos)));
        }


    }


    public WowmaApiRes getOrderByOrderId(PlatformStoreDo storeDo, String orderNumber) {
        String url = "https://api.manager.wowma.jp/wmshopapi/searchTradeInfoProc";
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("shopId", storeDo.getSellerId());
        bodyMap.put("orderId", orderNumber);
        List<OrderWowmaEntity> entities = new ArrayList<>();

        String jsonData = null;
        try {
            jsonData = WowmaUtil.raAPidoGet(url, storeDo.getAppSecret(), bodyMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(jsonData)) {
            return new WowmaApiRes(500, "Wowma店铺：" + storeDo.getStoreName() + "连接超时");
        }
        JSONObject object = null;
        List<OrderWowmaEntity> list = null;
        try {
            object = XmlUtils.xml2Json(jsonData);
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
        if (object == null || object.get("response") == null || object.getJSONObject("response").getString("result") == null) {
            return new WowmaApiRes(500, "Wowma 获取订单列表 xml格式解析空指针");
        }
        JSONObject result = object.getJSONObject("response").getJSONArray("result").getJSONObject(0);
        if (StringUtils.isBlank(result.getString("status"))) {
            return new WowmaApiRes(500, "Wowma 获取订单列表 status 获取失败");
        } else if ("1".equals(result.getString("status"))) {
            JSONObject error = result.getJSONArray("error").getJSONObject(0);
            if ("0002".equals(error.getString("code"))) {
                //message -> 認証に失敗しました。 授权过期了

            }
            return new WowmaApiRes(500, error.getString("message"));
        } else {
            list = JSONArray.parseArray(object.getJSONObject("response").getString("orderInfo"), OrderWowmaEntity.class);
        }
        return new WowmaApiRes(200, list, null);
    }

    @Override
    public void consumerUpdate(RakutenOrderUpdateConReq req) {
        if (CollUtil.isEmpty(req.getEts())) {
            return;
        }
        for (PlatformOrderDo et : req.getEts()) {
            platformOrderDao.updateById(et);
        }
        List<String> collect = req.getEts().stream().filter(et -> et.getStatus() != null && et.getStatus() == 4).map(PlatformOrderDo::getPlatformOrderNo).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            return;
        }
        rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_CancelForBound, JSON.toJSONString(new PlatformOrderCancelReq(req.getEts().get(0).getStoreId(), collect)));
    }

    @Override
    public void makeShip(WowmaMarkShipConsumerReq req) {
        PlatformStoreDo storeDo = platformStoreDao.selectById(req.getStoreId());
        if (storeDo == null) {
            return;
        }
        Map<String, List<Long>> failMap = new HashMap<>();
        List<Long> successId = new ArrayList<>();
        List<WowmaMarkStatusReq> markStatusReqList = new ArrayList<>();
        List<OperateRecordDo> operateRecordDos = new ArrayList<>();
        String url = "https://api.manager.wowma.jp/wmshopapi/updateTradeInfoProc";
        for (WowmaMarkShipReq mark : req.getMarks()) {
            WowmaMakeShipEntity entity = new WowmaMakeShipEntity(storeDo.getSellerId(), mark.getOrderNo(), DateUtils.dateFormatToString(mark.getShipTime()), mark.getLogisticsCarrier(), mark.getTrackNo().split(",")[0].replaceAll("-", "").trim());
            String string = XmlUtils.convertToXml(entity, "", "");
//            log.error("wowma标发开始，参数：" + string);
            String body = null;
            try {
                // Content-Type	: application/xml; charset=utf-8
                body = WowmaUtil.raAPidoPOSTXml(url, storeDo.getAppSecret(), "application/xml; charset=utf-8", string);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            log.error("wowma标发結束，返回：" + body);
            if (StringUtils.isBlank(body)) {
                failMap.computeIfAbsent("wowma服务器连接超时", k -> new ArrayList<>()).add(mark.getId());
            }
            JSONObject object = null;
            List<OrderWowmaEntity> list = null;
            try {
                object = XmlUtils.xml2Json(body);
            } catch (JDOMException | IOException e) {
                e.printStackTrace();
            }

            JSONObject result = object.getJSONObject("response").getJSONArray("result").getJSONObject(0);
            if (StringUtils.isBlank(result.getString("status"))) {
                failMap.computeIfAbsent("wowma status获取失败", k -> new ArrayList<>()).add(mark.getId());
            } else if ("1".equals(result.getString("status"))) {
                JSONObject error = result.getJSONArray("error").getJSONObject(0);
                if ("0002".equals(error.getString("code"))) {
                    //message -> 認証に失敗しました。 授权过期了
                }
                failMap.computeIfAbsent(error.getString("message"), k -> new ArrayList<>()).add(mark.getId());

                OperateRecordDo operateRecordDo = new OperateRecordDo(mark.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_MarkShip_Fail,
                        req.getUserId(), new Date(), error.getString("code") + "_" + error.getString("message"));
                operateRecordDos.add(operateRecordDo);
            } else {
                successId.add(mark.getId());
                markStatusReqList.add(new WowmaMarkStatusReq(mark.getId(), mark.getOrderNo()));
                OperateRecordDo operateRecordDo = new OperateRecordDo(mark.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_MarkShip, req.getUserId(), new Date(), mark.getTrackNo());
                operateRecordDos.add(operateRecordDo);
            }
        }
        if (!successId.isEmpty()) {
            platformOrderService.updateMarkStatusForFinish(successId, 3, null, StaticDict.Store_PlatformCode.Wowma.getValue());
        }
        for (String failReason : failMap.keySet()) {
            platformOrderService.updateMarkStatus(failMap.get(failReason), 2, failReason);
        }
        //回传单号后 去标记订单已完成
        if (!markStatusReqList.isEmpty()) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_MarkStatus, JSON.toJSONString(new WowmaMarkStatusConsumer(markStatusReqList, "完了", storeDo, req.getUserId())));
        }
        //操作记录
        if (!operateRecordDos.isEmpty()) {
            List<List<OperateRecordDo>> partition = ListUtil.partition(operateRecordDos, 3000);
            for (List<OperateRecordDo> partList : partition) {
                rabbitTemplate.convertAndSend(RabbitQueueConstant.CrossMall_CMOrder_OperateList, JSON.toJSONString(partList));
            }
        }
    }


    @Override
    public void makeStatus(WowmaMarkStatusConsumer req) {
        PlatformStoreDo storeDo = req.getStoreDo();
        Map<String, List<Long>> failMap = new HashMap<>();
        List<Long> successId = new ArrayList<>();
        List<OperateRecordDo> operateRecordDos = new ArrayList<>();
        String url = "https://api.manager.wowma.jp/wmshopapi/updateTradeStsProc";
        for (WowmaMarkStatusReq mark : req.getList()) {
            WowmaMarkFinishEntity entity = new WowmaMarkFinishEntity(storeDo.getSellerId(), mark.getOrderId(), req.getOrderStatus());
            String string = XmlUtils.convertToXml(entity, "", "");
//            log.error("wowma标记状态开始，参数：" + string);
            String body = null;
            try {
                // Content-Type	: application/xml; charset=utf-8
                body = WowmaUtil.raAPidoPOSTXml(url, storeDo.getAppSecret(), "application/xml; charset=utf-8", string);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            log.error("wowma标记状态结束，返回：" + body);
            if (StringUtils.isBlank(body)) {
                failMap.computeIfAbsent("wowma服务器连接超时", k -> new ArrayList<>()).add(mark.getId());
            }
            JSONObject object = null;
            List<OrderWowmaEntity> list = null;
            try {
                object = XmlUtils.xml2Json(body);
            } catch (JDOMException | IOException e) {
                e.printStackTrace();
            }

            JSONObject result = object.getJSONObject("response").getJSONArray("result").getJSONObject(0);
            if (StringUtils.isBlank(result.getString("status"))) {
                failMap.computeIfAbsent("wowma status获取失败", k -> new ArrayList<>()).add(mark.getId());
            } else if ("1".equals(result.getString("status"))) {
                JSONObject error = result.getJSONArray("error").getJSONObject(0);
                if ("0002".equals(error.getString("code"))) {
                    //message -> 認証に失敗しました。 授权过期了
                }
                failMap.computeIfAbsent(error.getString("message"), k -> new ArrayList<>()).add(mark.getId());
                OperateRecordDo operateRecordDo = new OperateRecordDo(mark.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_MarkFinish_Fail,
                        req.getUserId(), new Date(), req.getOrderStatus() + SysConstant.operateRecordSeparator + error.getString("code") + "_" + error.getString("message"));
                operateRecordDos.add(operateRecordDo);
            } else {
                successId.add(mark.getId());
                OperateRecordDo operateRecordDo = new OperateRecordDo(mark.getId(), OperateTypeEnum.PlatformOrder.getValue(), SysConstant.platformOrder_MarkFinish, req.getUserId(), new Date(), req.getOrderStatus());
                operateRecordDos.add(operateRecordDo);
            }
        }
        if (!successId.isEmpty()) {
            int mailType = 1;
            Integer markFinishStatus = null;
            if ("完了".equals(req.getOrderStatus())) {
                markFinishStatus = 3;
                mailType = 2;
            } else if ("与信待ち".equals(req.getOrderStatus()) || "発送待ち".equals(req.getOrderStatus())) {
                markFinishStatus = 30;
                mailType = 1;
            }
            if (markFinishStatus != null) {
                LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<PlatformOrderDo>();
                updateWrapper.in(PlatformOrderDo::getId, successId);
                updateWrapper.set(PlatformOrderDo::getMarkFinishStatus, markFinishStatus);
                updateWrapper.set(PlatformOrderDo::getMarkShipmentFailReason, null);
                updateWrapper.setSql(markFinishStatus == 30, String.format(" pay_time = (case when pay_time is null then '%1$s' else pay_time end)", DateUtils.dateFormatToString(new Date(), "yyyy-MM-dd hh:mm:ss")));
                this.update(updateWrapper);
            }
            int mailTypef = mailType;
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformOrder_Auto_SendMail, JSON.toJSONString(new SendMailConsumerReq(mailTypef, storeDo.getId(), successId)));
        }

        Integer failMarkStatus = null;
        if ("完了".equals(req.getOrderStatus())) {
            failMarkStatus = 2;
        } else if ("与信待ち".equals(req.getOrderStatus()) || "発送待ち".equals(req.getOrderStatus())) {
            failMarkStatus = 20;
        }
        if (failMarkStatus != null) {
            for (String failReason : failMap.keySet()) {
                LambdaUpdateWrapper<PlatformOrderDo> updateWrapper = new LambdaUpdateWrapper<PlatformOrderDo>();
                updateWrapper.in(PlatformOrderDo::getId, failMap.get(failReason));
                updateWrapper.set(PlatformOrderDo::getMarkShipmentFailReason, failReason);
                updateWrapper.set(PlatformOrderDo::getMarkFinishStatus, failMarkStatus);
                this.update(updateWrapper);
            }
        }
        //操作记录
        if (!operateRecordDos.isEmpty()) {
            List<List<OperateRecordDo>> partition = ListUtil.partition(operateRecordDos, 3000);
            for (List<OperateRecordDo> partList : partition) {
                rabbitTemplate.convertAndSend(RabbitQueueConstant.CrossMall_CMOrder_OperateList, JSON.toJSONString(partList));
            }
        }
    }


    @Override
    public void makeFinish() {
        List<PlatformOrderDo> platformOrderDoList = platformOrderDao.selectList(new LambdaQueryWrapper<PlatformOrderDo>()
                .select(PlatformOrderDo::getId, PlatformOrderDo::getPlatformOrderNo, PlatformOrderDo::getMarkFinishStatus, PlatformOrderDo::getStoreId)
                .eq(PlatformOrderDo::getStatus, 3)
                .eq(PlatformOrderDo::getMarkFinishStatus, 5).eq(PlatformOrderDo::getPlatformCode, "wowma")
                .gt(PlatformOrderDo::getMarkShipmentTime, DateUtils.dateFormatToString(DateUtils.passingDate(new Date(), -3))));
        Map<Long, List<PlatformOrderDo>> collect = platformOrderDoList.stream().collect(Collectors.groupingBy(PlatformOrderDo::getStoreId));
        for (Long l : collect.keySet()) {
            PlatformStoreDo storeDo = platformStoreService.getById(l);
            List<WowmaMarkStatusReq> markStatusReqList = new ArrayList<>();
            for (PlatformOrderDo orderDo : collect.get(l)) {
                markStatusReqList.add(new WowmaMarkStatusReq(orderDo.getId(), orderDo.getPlatformOrderNo()));
            }
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformStore_Wowma_MarkStatus, JSON.toJSONString(new WowmaMarkStatusConsumer(markStatusReqList, "完了", storeDo, null)));
        }
    }



    @Override
    public void setStockByStoreId(StockToPlatformConsumerReq req) {
        PlatformStoreDo storeDo = platformStoreDao.selectById(req.getStoreId());
        if (storeDo == null) {
            return;
        }
        AsyncJobDo asyncJobDo = asyncJobDao.selectById(req.getJobId());
        if (asyncJobDo == null) {
            return;
        }
        //告诉他正在处理
        rabbitTemplate.convertAndSend(RabbitQueueConstant.Export_AsyncDo_Update, JSON.toJSONString(new AsyncUpdateConsumerReq(req.getJobId(), 1, 0, null)));
        List<PlatformSkuStockDto> skuStockList = productStockDao.getPlatformSkuStockList(Collections.singletonList(StaticDict.Store_PlatformCode.Wowma.getValue()),
                null, req.getParentSKuList(), req.getInventoryLink(), Collections.singletonList(req.getStoreId()));
//        skuStockList.add(new PlatformSkuStockDto(2005L, "kw-1k2s14", "kw-1", 0.05d, 10));
        if (skuStockList.isEmpty()) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.Export_AsyncDo_Finish, JSON.toJSONString(new AsyncFinishConsumerReq(req.getJobId(), null)));
            return;
        }

        Map<String, List<PlatformSkuStockDto>> parentSkuMap = skuStockList.stream().filter(skuStock -> StringUtils.isNotBlank(skuStock.getParentSku())).collect(Collectors.groupingBy(PlatformSkuStockDto::getParentSku));
        List<WowmaStockUpdateItemReq> stockList = new ArrayList<>();
        String stockRedisKey = RedisKeyConstants.PLATFORMSTOCK_KEY_PREFIX +customer +"_"+ req.getStoreId();
        Map<Long, Integer> small20IdToQuantityMap = new HashMap<>();
        parentSku:
        for (String parentSku : parentSkuMap.keySet()) {
            if (StringUtils.isBlank(parentSku)) {
                continue;
            }
            Map<String, Integer> skuQtyMap = new HashMap<>();
            List<PlatformSkuStockDto> skuList = parentSkuMap.get(parentSku);
            boolean allSame = true;
            for (PlatformSkuStockDto skuStock : skuList) {
//                if (skuStock.getHideItem() != null && skuStock.getHideItem() == 1) {
//                    continue parentSku;
//                }
                double stockPercent = skuStock.getStockPercent() < 0 || skuStock.getStockPercent() > 1 ? 0.95 : 1 - skuStock.getStockPercent();
                int quantity = (int) (skuStock.getLeftQty() / skuStock.getQty() * stockPercent);
                quantity = Math.min(Math.max(quantity, 0), 99999);
                if (quantity > 0 && quantity <= 20) {
                    small20IdToQuantityMap.put(skuStock.getId(), quantity); // 保存ID与库存的映射
                }
                if (quantity <= 20 && req.getUserId() == null) {
                    quantity = 0;
                }
                Integer lastQuantity = platformOrderService.getLastRecordedInventory(stockRedisKey, skuStock.getPlatformSku());
                if (lastQuantity == null || !lastQuantity.equals(quantity)) {
                    allSame = false;
                }
                skuQtyMap.put(skuStock.getPlatformSku(), quantity);
            }
            if (allSame && req.getUserId() == null) {//管理番号下 平台回传数量和上一次全部一致 则不用回传 且是自动
                continue;
            }
            //通常在库
            List<WowmaChoicesStockHorizontal> choicesStockHorizontals = new ArrayList<>();
            List<WowmaChoicesStockVertical> choicesStockVerticals = new ArrayList<>();
            List<WowmaChoiceStockEntity> choicesStocks = new ArrayList<>();
            for (PlatformSkuStockDto skuStock : skuList) {
                //一个管理番号下 需要全部回传 不可以部分回传
                Integer quantity = skuQtyMap.get(skuStock.getPlatformSku());
                if (quantity == null) {
                    quantity = 0;
                }
                if (skuList.size() == 1 && Objects.equals(skuStock.getPlatformSku(), parentSku)) {
                    stockList.add(new WowmaStockUpdateItemReq(skuStock.getParentSku(), "1", quantity + "", skuStock.getShippingDayId(), "1"));
                    continue parentSku;
                }
                else {
                    if (StringUtils.isNotBlank(skuStock.getHorizontalItemName()) && StringUtils.isNotBlank(skuStock.getOptionValue1()) && StringUtils.isNotBlank(skuStock.getOptionName1()) && StringUtils.isNotBlank(skuStock.getOptionHorizontalSeq())) {
                        choicesStockHorizontals.add(new WowmaChoicesStockHorizontal(skuStock.getOptionValue1(), skuStock.getOptionName1(), skuStock.getOptionHorizontalSeq()));
                    }
                    if (StringUtils.isNotBlank(skuStock.getVerticalItemName()) && StringUtils.isNotBlank(skuStock.getOptionValue2()) && StringUtils.isNotBlank(skuStock.getOptionName2()) && StringUtils.isNotBlank(skuStock.getOptionVerticalSeq())) {
                        choicesStockVerticals.add(new WowmaChoicesStockVertical(skuStock.getOptionValue2(), skuStock.getOptionName2(), skuStock.getOptionVerticalSeq()));
                    }
                    choicesStocks.add(new WowmaChoiceStockEntity(skuStock.getOptionValue1(), skuStock.getOptionValue2(), quantity + "", skuStock.getShippingDayId()));
                }
            }
            //choicesStockHorizontals 和 choicesStockVerticals 要去重
            choicesStockHorizontals = choicesStockHorizontals.stream().filter(distinctByKey(WowmaChoicesStockHorizontal::getChoicesStockHorizontalCode)).collect(Collectors.toList());
            choicesStockVerticals = choicesStockVerticals.stream().filter(distinctByKey(WowmaChoicesStockVertical::getChoicesStockVerticalCode)).collect(Collectors.toList());
            if (!choicesStockHorizontals.isEmpty() || !choicesStockVerticals.isEmpty()) {
                String horizontalItemName = choicesStockHorizontals.isEmpty() ? null : skuList.get(0).getHorizontalItemName();
                String verticalItemName = choicesStockVerticals.isEmpty() ? null : skuList.get(0).getVerticalItemName();
                stockList.add(new WowmaStockUpdateItemReq(parentSku, "2", "1", horizontalItemName, choicesStockHorizontals,
                        verticalItemName, choicesStockVerticals, choicesStocks));
            }
        }
        String url = "https://api.manager.wowma.jp/wmshopapi/updateStock";
        try {
            String key = asyncJobDo.getJobType() + "_count_"  + "_" + asyncJobDo.getCompanyId() + "_" + customer + "_" + DateUtils.dateFormatToString(new Date(), "yyyyMMdd");
            long count = redisTemplate.opsForValue().increment(key, 1);
            redisTemplate.expire(key, 60 * 60 * 25, TimeUnit.SECONDS);
            String fileName = asyncJobDo.getJobName() + "_" + count + ".csv";
            String tempFilePath = omsFilePath + fileName;
            CsvExportParams csvParam = new CsvExportParams();
//            csvParam.setEncoding("Shift-JIS");
            csvParam.setEncoding("UTF-8");
            csvParam.setTextMark("");
            CsvUtils.initCsv(tempFilePath, csvParam, StockToPlatformRecordVo.class);
            Map<String, String> errorMap = new HashMap<>();
            List<List<WowmaStockUpdateItemReq>> partition = ListUtil.partition(stockList, 200);
            for (List<WowmaStockUpdateItemReq> inventoryRakutenEntities : partition) {
                List<WowmaStockUpdateItemEntity> entityList = inventoryRakutenEntities.stream()
                        .map(i -> new WowmaStockUpdateItemEntity(i.getItemCode(), i.getStockSegment(), i.getStockCount(), i.getStockShippingDayId(), i.getChoicesStockHorizontalItemName(),
                                i.getChoicesStockHorizontals(), i.getChoicesStockVerticalItemName(), i.getChoicesStockVerticals(), i.getChoicesStocks()))
                        .collect(Collectors.toList());
                WowmaUpdateStockEntity entity = new WowmaUpdateStockEntity(storeDo.getSellerId(), entityList);
                log.info("wowma回传库存开始 参数(json)：" + JSON.toJSONString(entity));
                String string = XmlUtils.convertToXml(entity, "", "");
                log.info("wowma回传库存开始，参数(xml)：" + string);
                String body = null;
                try {
                    // Content-Type	: application/xml; charset=utf-8
                    body = WowmaUtil.raAPidoPOSTXml(url, storeDo.getAppSecret(), "application/xml; charset=utf-8", string);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response><result><status>1</status></result><updateResult><itemCode>e1-3-4-e8</itemCode><error><code>PME0134</code><message>対象のデータが存在しません。</message></error></updateResult></response>
                log.info("wowma同步库存返回值json：" + body);
                String errorMsg = null;
                if (StringUtils.isBlank(body)) {
                    errorMsg = "wowma服务器连接超时";
                }
                else {
                    JSONObject object = null;
                    List<OrderWowmaEntity> list = null;
                    try {
                        object = XmlUtils.xml2Json(body);
                    } catch (JDOMException | IOException e) {
                        e.printStackTrace();
                    }
                    if (object == null) {
                        errorMsg = "wowma 同步库存 xml格式解析空指针";
                    }
                    if(object != null) {
                        JSONObject result = object.getJSONObject("response").getJSONArray("result").getJSONObject(0);
                        if (StringUtils.isBlank(result.getString("status"))) {
                            errorMsg = ("wowma status获取失败");
                        } else if ("1".equals(result.getString("status"))) {
                            //可能全部失败 可能部分成功
                            JSONArray updateResultArray = object.getJSONObject("response").getJSONArray("updateResult");
                            for (int i = 0; i < updateResultArray.size(); i++) {
                                JSONObject updateResult = updateResultArray.getJSONObject(i);
                                String itemCode = updateResult.getString("itemCode");
                                JSONArray error = updateResult.getJSONArray("error");
                                if (error != null && !error.isEmpty()) {
                                    errorMap.put(itemCode, error.getJSONObject(0).getString("code") + ":" + error.getJSONObject(0).getString("message"));
                                }
                            }
//                            if ("0002".equals(error.getString("code"))) {
//                                //message -> 認証に失敗しました。 授权过期了
//                            }
                        } else {
                            //成功
                            JSONArray updateResult = object.getJSONObject("response").getJSONArray("updateResult");
                            for (int i = 0; i < updateResult.size(); i++) {
                                JSONObject updateResultEntity = updateResult.getJSONObject(i);
                                String itemCode = updateResultEntity.getString("itemCode");
                                JSONArray error = updateResultEntity.getJSONArray("error");

                            }
                        }
                    }
                }

                List<StockToPlatformRecordVo> list = new ArrayList<>();
                Map<String, String> thisStockMap = new HashMap<>();
                for (WowmaStockUpdateItemReq inventoryRakutenEntity : inventoryRakutenEntities) {
                    String error = errorMap.get(inventoryRakutenEntity.getItemCode());
                    if (Objects.equals(inventoryRakutenEntity.getStockSegment(), "1")) {
                        int stockCount = 0;
                        if (StringUtils.isNotBlank(inventoryRakutenEntity.getStockCount())) {
                            stockCount = Integer.parseInt(inventoryRakutenEntity.getStockCount());
                        }
                        //通常在苦
                        if (StringUtils.isBlank(errorMsg) && StringUtils.isBlank(error)) {
                            //成功
                            list.add(new StockToPlatformRecordVo(inventoryRakutenEntity.getItemCode(), inventoryRakutenEntity.getItemCode(), stockCount, "成功", null));
                            thisStockMap.put(inventoryRakutenEntity.getItemCode(), String.valueOf(stockCount));
                        }
                        else {
                            list.add(new StockToPlatformRecordVo(inventoryRakutenEntity.getItemCode(), inventoryRakutenEntity.getItemCode(), stockCount, "失败", StringUtils.isBlank(errorMsg) ? error : errorMsg));
                        }
                    }
                    else {
                        for (WowmaChoiceStockEntity choicesStock : inventoryRakutenEntity.getChoicesStocks()) {
                            int stockCount = 0;
                            if (StringUtils.isNotBlank(choicesStock.getChoicesStockCount())) {
                                stockCount = Integer.parseInt(choicesStock.getChoicesStockCount());
                            }
                            String platformSku = inventoryRakutenEntity.getItemCode() + choicesStock.getChoicesStockHorizontalCode() + choicesStock.getChoicesStockVerticalCode();
                            if (StringUtils.isBlank(errorMsg) && StringUtils.isBlank(error)) {
                                //成功
                                list.add(new StockToPlatformRecordVo(inventoryRakutenEntity.getItemCode(), platformSku, stockCount, "成功", null));
                                thisStockMap.put(platformSku, String.valueOf(stockCount));
                            }
                            else {
                                list.add(new StockToPlatformRecordVo(inventoryRakutenEntity.getItemCode(), platformSku, stockCount, "失败", StringUtils.isBlank(errorMsg) ? error : errorMsg));
                            }
                        }
                    }
                }
                if (!thisStockMap.isEmpty() && req.getUserId() == null) {
                    //记录本次回传数量至redis
                    redisTemplate.opsForHash().putAll(stockRedisKey, thisStockMap);
//                    redisTemplate.expire(stockRedisKey, 8, TimeUnit.HOURS);
                }
                CsvUtils.appendToCsv(tempFilePath, list);
                rabbitTemplate.convertAndSend(RabbitQueueConstant.Export_AsyncDo_Update, JSON.toJSONString(new AsyncUpdateConsumerReq(req.getJobId(), null, list.size(), null)));
            }
            //本机文件传到oms上
            String objectNameTemporary = "";
            if (filePath.startsWith("http")) {
                try {
                    objectNameTemporary = AliOss.temporaryFile2(fileName, new File(tempFilePath));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("导出文件失败" + e.getMessage());
                }
            }
            //文件路径
            String path = fileUrl + objectNameTemporary;
            rabbitTemplate.convertAndSend(RabbitQueueConstant.Export_AsyncDo_Finish, JSON.toJSONString(new AsyncFinishConsumerReq(req.getJobId(), path)));
        } catch (Exception e) {
            e.printStackTrace();
            rabbitTemplate.convertAndSend(RabbitQueueConstant.Export_AsyncDo_Update, JSON.toJSONString(new AsyncUpdateConsumerReq(req.getJobId(), 4, 0, e.getMessage())));
        }
        //用ZSet处理低库存SKU的存储与对比
        rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformProduct_InventoryLess, JSON.toJSONString(new UpdateInventoryLessReq(req.getStoreId(), req.getUserId(), small20IdToQuantityMap)));
    }

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        //putIfAbsent方法添加键值对，如果map集合中没有该key对应的值，则直接添加，并返回null，如果已经存在对应的值，则依旧为原来的值。
        //如果返回null表示添加数据成功(不重复)，不重复(null==null :TRUE)
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    @Override
    public void syncItems() {
        List<PlatformStoreDo> storeDoList = platformStoreDao.selectList(new LambdaQueryWrapper<PlatformStoreDo>().eq(PlatformStoreDo::getPlatformCode, "wowma")
                .eq(PlatformStoreDo::getAuthSyncStatus, 1).isNotNull(PlatformStoreDo::getAppSecret));
        for (PlatformStoreDo storeDo : storeDoList) {
            rabbitTemplate.convertAndSend(RabbitQueueConstant.GetPlatformProduct_Wowma, JSON.toJSONString(new ItemUpdateConsumerReq(storeDo, null, null)));
        }
    }


    @Override
    public void searchItemInfos(PlatformStoreDo storeDo, String parentSku) {
        String url = "https://api.manager.wowma.jp/wmshopapi/searchItemInfos"; // searchStocks
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("shopId", storeDo.getSellerId());
        if (StringUtils.isNotBlank(parentSku)) {
            bodyMap.put("itemCode", parentSku);
        }
        int totalCount = 500;//最大500
        bodyMap.put("totalCount", totalCount);
        int startCount = 1;
        int resultCount = 0;
        List<WowmaResultItemEntity> entityList = new ArrayList<>();
        do {
            bodyMap.put("startCount", startCount);
            String jsonData = null;
            try {
                jsonData = WowmaUtil.raAPidoGet(url, storeDo.getAppSecret(), bodyMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject object = null;
            List<WowmaResultItemEntity> list = null;
            try {
                object = XmlUtils.xml2Json(jsonData);
            } catch (JDOMException | IOException e) {
                e.printStackTrace();
            }
            if (object == null || object.get("response") == null || object.getJSONObject("response").getString("result") == null) {
                break;
            }
            JSONObject result = object.getJSONObject("response").getJSONArray("result").getJSONObject(0);
            if (StringUtils.isBlank(result.getString("status"))) {
                break;
            } else if ("1".equals(result.getString("status"))) {
                JSONObject error = result.getJSONArray("error").getJSONObject(0);
                break;
            } else {
                resultCount = object.getJSONObject("response").getJSONArray("searchResult").getJSONObject(0).getIntValue("resultCount");
                list = JSONArray.parseArray(object.getJSONObject("response").getJSONArray("searchResult").getJSONObject(0).getString("resultItems"), WowmaResultItemEntity.class);
                startCount += resultCount;
                if (!CollUtil.isEmpty(list)) {
                    entityList.addAll(list);
                }
            }
        } while (resultCount >= totalCount);

        List<PlatformProductDo> productDoList = new ArrayList<>();
        for (WowmaResultItemEntity itemEntity : entityList) {
            RegisterStockEntity resultStock = itemEntity.getRegisterStock().get(0);
            if (Objects.equals(resultStock.getStockSegment(), "1")) {
                //通常在库
                PlatformProductDo productDo = new PlatformProductDo();
                productDo.setStoreId(storeDo.getId());
                productDo.setCompanyId(storeDo.getCompanyId());
                productDo.setTenantId(storeDo.getTenantId());
                productDo.setItemName(itemEntity.getItemName());
                if (StringUtils.isNotBlank(itemEntity.getItemPrice())) {
                    productDo.setPrice(new BigDecimal(itemEntity.getItemPrice()));
                }
                productDo.setParentSku(itemEntity.getItemCode());
                productDo.setHideItem(Objects.equals(itemEntity.getSaleStatus(), "1") ? 0 : 1);
                productDo.setItemName(null);
                productDo.setPlatformSku(itemEntity.getItemCode());
                productDo.setShippingDayId(resultStock.getStockShippingDayId());
                productDoList.add(productDo);
            } else if (Objects.equals(resultStock.getStockSegment(), "2")) {
                if (CollUtil.isNotEmpty(resultStock.getChoicesStockHorizontals()) && CollUtil.isNotEmpty(resultStock.getChoicesStockVerticals())) {
                    for (WowmaChoicesStockHorizontal choicesStockHorizontal : resultStock.getChoicesStockHorizontals()) {
                        for (WowmaChoicesStockVertical choicesStockVertical : resultStock.getChoicesStockVerticals()) {
                            //sku = itemCode + Horizontal + Vertical
                            PlatformProductDo productDo = new PlatformProductDo();
                            productDo.setStoreId(storeDo.getId());
                            productDo.setCompanyId(storeDo.getCompanyId());
                            productDo.setTenantId(storeDo.getTenantId());
                            productDo.setParentSku(itemEntity.getItemCode());
                            productDo.setItemName(itemEntity.getItemName());
                            if (StringUtils.isNotBlank(itemEntity.getItemPrice())) {
                                productDo.setPrice(new BigDecimal(itemEntity.getItemPrice()));
                            }
                            productDo.setHideItem(Objects.equals(itemEntity.getSaleStatus(), "1") ? 0 : 1);
                            productDo.setItemName(null);
                            String platformSku = itemEntity.getItemCode() + choicesStockHorizontal.getChoicesStockHorizontalCode() + choicesStockVertical.getChoicesStockVerticalCode();
                            productDo.setPlatformSku(platformSku);
                            productDo.setHorizontalItemName(resultStock.getChoicesStockHorizontalItemName());
                            productDo.setVerticalItemName(resultStock.getChoicesStockVerticalItemName());
                            productDo.setOptionName1(choicesStockHorizontal.getChoicesStockHorizontalName());
                            productDo.setOptionValue1(choicesStockHorizontal.getChoicesStockHorizontalCode());
                            productDo.setOptionName2(choicesStockVertical.getChoicesStockVerticalName());
                            productDo.setOptionValue2(choicesStockVertical.getChoicesStockVerticalCode());
                            productDo.setOptionHorizontalSeq(choicesStockHorizontal.getChoicesStockHorizontalSeq());
                            productDo.setOptionVerticalSeq(choicesStockVertical.getChoicesStockVerticalSeq());
                            //发送日情报
                            List<String> dayId = resultStock.getChoicesStocks().stream().filter(i -> Objects.equals(i.getChoicesStockHorizontalCode(), choicesStockHorizontal.getChoicesStockHorizontalCode())
                                    && Objects.equals(i.getChoicesStockVerticalCode(), choicesStockVertical.getChoicesStockVerticalCode()) && StringUtils.isNotBlank(i.getChoicesStockShippingDayId())).map(WowmaChoiceStockEntity::getChoicesStockShippingDayId).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(dayId)) {
                                productDo.setShippingDayId(dayId.get(0));
                            }
                            productDoList.add(productDo);
                        }
                    }
                } else if (CollUtil.isNotEmpty(resultStock.getChoicesStockHorizontals())) {
                    for (WowmaChoicesStockHorizontal choicesStockHorizontal : resultStock.getChoicesStockHorizontals()) {
                        PlatformProductDo productDo = new PlatformProductDo();
                        productDo.setStoreId(storeDo.getId());
                        productDo.setCompanyId(storeDo.getCompanyId());
                        productDo.setTenantId(storeDo.getTenantId());
                        productDo.setParentSku(itemEntity.getItemCode());
                        productDo.setItemName(itemEntity.getItemName());
                        if (StringUtils.isNotBlank(itemEntity.getItemPrice())) {
                            productDo.setPrice(new BigDecimal(itemEntity.getItemPrice()));
                        }
                        productDo.setHideItem(Objects.equals(itemEntity.getSaleStatus(), "1") ? 0 : 1);
                        productDo.setItemName(null);
                        String platformSku = itemEntity.getItemCode() + choicesStockHorizontal.getChoicesStockHorizontalCode();
                        productDo.setPlatformSku(platformSku);
                        productDo.setHorizontalItemName(resultStock.getChoicesStockHorizontalItemName());
                        productDo.setVerticalItemName("");
                        productDo.setOptionName1(choicesStockHorizontal.getChoicesStockHorizontalName());
                        productDo.setOptionValue1(choicesStockHorizontal.getChoicesStockHorizontalCode());
                        productDo.setOptionHorizontalSeq(choicesStockHorizontal.getChoicesStockHorizontalSeq());
                        productDo.setOptionName2("");
                        productDo.setOptionValue2("");
                        productDo.setOptionVerticalSeq("");
                        //发送日情报
                        List<String> dayId = resultStock.getChoicesStocks().stream().filter(i -> Objects.equals(i.getChoicesStockHorizontalCode(), choicesStockHorizontal.getChoicesStockHorizontalCode())&& StringUtils.isNotBlank(i.getChoicesStockShippingDayId()))
                                .map(WowmaChoiceStockEntity::getChoicesStockShippingDayId).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(dayId)) {
                            productDo.setShippingDayId(dayId.get(0));
                        }
                        productDoList.add(productDo);
                    }
                } else if (CollUtil.isNotEmpty(resultStock.getChoicesStockVerticals())) {
                    for (WowmaChoicesStockVertical choicesStockVertical : resultStock.getChoicesStockVerticals()) {
                        PlatformProductDo productDo = new PlatformProductDo();
                        productDo.setStoreId(storeDo.getId());
                        productDo.setCompanyId(storeDo.getCompanyId());
                        productDo.setTenantId(storeDo.getTenantId());
                        productDo.setParentSku(itemEntity.getItemCode());
                        productDo.setHideItem(Objects.equals(itemEntity.getSaleStatus(), "1") ? 0 : 1);
                        productDo.setItemName(null);
                        String platformSku = itemEntity.getItemCode() + choicesStockVertical.getChoicesStockVerticalCode();
                        productDo.setPlatformSku(platformSku);
                        productDo.setHorizontalItemName("");
                        productDo.setVerticalItemName(resultStock.getChoicesStockVerticalItemName());
                        productDo.setOptionName2(choicesStockVertical.getChoicesStockVerticalName());
                        productDo.setOptionValue2(choicesStockVertical.getChoicesStockVerticalCode());
                        productDo.setOptionVerticalSeq(choicesStockVertical.getChoicesStockVerticalSeq());
                        productDo.setOptionName1("");
                        productDo.setOptionValue1("");
                        productDo.setOptionHorizontalSeq("");
                        //发送日情报
                        List<String> dayId = resultStock.getChoicesStocks().stream().filter(i -> Objects.equals(i.getChoicesStockVerticalCode(), choicesStockVertical.getChoicesStockVerticalCode())&& StringUtils.isNotBlank(i.getChoicesStockShippingDayId()))
                                .map(WowmaChoiceStockEntity::getChoicesStockShippingDayId).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(dayId)) {
                            productDo.setShippingDayId(dayId.get(0));
                        }
                        productDoList.add(productDo);
                    }
                }
            }
        }
        Map<String, List<PlatformProductDo>> parentSkuMap = productDoList.stream().filter(productDo -> StringUtils.isNotBlank(productDo.getParentSku())).collect(Collectors.groupingBy(PlatformProductDo::getParentSku));
        if (StringUtils.isBlank(parentSku) && !parentSkuMap.isEmpty()) {
            //全量同步时 根据管理番号去删除
            LambdaQueryWrapper<PlatformProductDo> selectWrapper = new LambdaQueryWrapper<>();
            selectWrapper.select(PlatformProductDo::getId);
            selectWrapper.notIn(PlatformProductDo::getParentSku, parentSkuMap.keySet());
            selectWrapper.eq(PlatformProductDo::getCompanyId, storeDo.getCompanyId());
            selectWrapper.eq(PlatformProductDo::getStoreId, storeDo.getId());
            List<PlatformProductDo> deleteDoList = platformProductService.getBaseMapper().selectList(selectWrapper);
            List<Long> ids = deleteDoList.stream().map(PlatformProductDo::getId).collect(Collectors.toList());
            if (!ids.isEmpty()) {
                LambdaUpdateWrapper<PlatformProductDo> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.in(PlatformProductDo::getId, ids);
                updateWrapper.set(PlatformProductDo::getDeleteFlag, 1);
                updateWrapper.set(PlatformProductDo::getDeleteBy, -2);
                updateWrapper.set(PlatformProductDo::getDeleteTime, new Date());
                platformProductService.update(updateWrapper);
            }
        }

        for (String parentSkuKey : parentSkuMap.keySet()) {
            boolean delete = true;
            rabbitTemplate.convertAndSend(RabbitQueueConstant.PlatformProduct_Rakuten_UpdateByParentSKu, JSON.toJSONString(new PlatformProductSyncReq(parentSkuMap.get(parentSkuKey),
                    StaticDict.Store_PlatformCode.Rakuten.getValue(), delete, storeDo.getId(), storeDo.getCompanyId())));
        }
    }
}
